<template>
  <v-content style="text-align: left">
    <v-layout>
      <v-flex xs3 class="overflow-auto type-background">
        <v-sheet class="left-color" :height="clientHeight">
          <v-card dark :height="clientHeight">
            <v-card-title class="subtitle-1">
              <v-tooltip right>
                <template v-slot:activator="{ on }">
                  <v-icon dark v-on="on">mdi-book-variant</v-icon>
                </template>
                <span>文章千古事，得失寸心知。</span>
              </v-tooltip>
            </v-card-title>
            <v-card-actions>
              <v-btn block circle outlined color="grey lighten-5" dark @click="alert = !alert">
                <v-icon>mdi-plus</v-icon>
                新建分类
              </v-btn>
            </v-card-actions>
            <div class="left-color">
              <v-alert
                :value="alert"
                color="#424242"
                dark
                icon="mdi-emoticon-happy"
                dense
                transition="scale-transition"
              >
                <v-form
                  ref="form"
                  v-model="valid"
                  :lazy-validation="lazy"
                >
                  <v-row>
                    <v-text-field
                      v-model="sortName"
                      dark
                      :counter="10"
                      :rules="nameRules"
                      label="分类名称"
                      required
                    />
                  </v-row>
                  <v-row>
                    <v-btn dark outlined @click="addBlogType">提交</v-btn>
                    <v-btn dark outlined class="ml-5" @click="alert = !alert">取消</v-btn>
                  </v-row>
                </v-form>
              </v-alert>
            </div>
            <v-card-text class="left-color">
              <!--文章分类的内容-->
              <v-list dense>
                <v-list-item-group v-model="typeList" color="primary">
                  <v-list-item
                    v-for="blog in blogTypes"
                    :key="blog.id"
                    @click="getBlogsByType(blog.id)"
                  >
                    <v-list-item-icon>
                      <v-icon v-text="blog.icon" />
                    </v-list-item-icon>
                    <v-list-item-content>
                      <v-list-item-title v-text="blog.name" />
                    </v-list-item-content>
                    <v-list-item-action>
                      <v-menu dark right close-on-click>
                        <template v-slot:activator="{ on }">
                          <v-btn
                            dark
                            color="#424242"
                            max-width="32"
                            fab
                            x-small
                            elevation="0"
                            v-on="on"
                          >
                            <v-icon>mdi-settings</v-icon>
                          </v-btn>
                        </template>
                        <v-list>
                          <v-list-item>
                            <v-list-item-title @click="openEditDialog(blog.id,blog.name)">
                              修改分类
                            </v-list-item-title>
                          </v-list-item>
                          <v-list-item
                            @click="deleteBlogType(blog.id)"
                          >
                            <v-list-item-title>删除分类</v-list-item-title>
                          </v-list-item>
                        </v-list>
                      </v-menu>
                    </v-list-item-action>
                  </v-list-item>
                </v-list-item-group>
              </v-list>
            </v-card-text>
          </v-card>
        </v-sheet>
      </v-flex>
      <v-flex class="overflow-auto type-background" xs3>
        <v-sheet dark :height="clientHeight">
          <v-card :height="clientHeight">
            <v-card-title class="subtitle-1">
              <v-tooltip right>
                <template v-slot:activator="{ on }">
                  <v-icon v-on="on">mdi-pen</v-icon>
                </template>
                <span>江湖儿女，谁无半点心事？</span>
              </v-tooltip>
            </v-card-title>
            <v-card-actions>
              <v-tooltip right>
                <template v-slot:activator="{ on }">
                  <v-btn
                    small
                    circle
                    fab
                    color="#424242"
                    @click="newArticle"
                  >
                    <v-icon v-on="on">mdi-plus</v-icon>
                  </v-btn>
                </template>
                <span>新建文章</span>
              </v-tooltip>
              <v-card-text class="caption">在下方新建文章</v-card-text>
            </v-card-actions>
            <v-divider />
            <!--文章分类的内容-->
            <v-list v-if="blogs && blogs.length > 0">
              <v-list-item-group v-model="articleList" color="primary">
                <v-list-item
                  v-for="(blog, i) in blogs"
                  :key="i"
                  @click="showEditorArea(blog)"
                >
                  <v-list-item-content>
                    <v-list-item-title :value="blogTitle">{{ blog.title }}</v-list-item-title>
                  </v-list-item-content>
                  <v-list-item-action>
                    <v-menu dark left close-on-click>
                      <template v-slot:activator="{ on }">
                        <v-btn
                          max-width="32"
                          fab
                          x-small
                          color="#424242"
                          elevation="0"
                          v-on="on"
                        >
                          <v-icon>mdi-settings</v-icon>
                        </v-btn>
                      </template>
                      <v-list>
                        <v-list-item
                          @click="deleteBlog(blog.id)"
                        >
                          <v-list-item-title>删除文章</v-list-item-title>
                        </v-list-item>
                      </v-list>
                    </v-menu>
                  </v-list-item-action>
                </v-list-item>
              </v-list-item-group>
            </v-list>
            <v-list v-else="" dense>
              <v-list-item-content />
            </v-list>
          </v-card>
        </v-sheet>
      </v-flex>
      <v-flex class="overflow-auto type-background" xs6>
        <v-sheet :height="clientHeight">
          <v-card v-if="editorShow" :height="clientHeight">
            <v-layout column>
              <v-flex>
                <v-row>
                  <v-col cols="9">
                    <v-text-field
                      v-model="blogTitle"
                      :counter="50"
                      :rules="blogNameRules"
                      label="文章标题"
                      prepend-icon="mdi-blogger"
                      clearable
                      required
                    />
                  </v-col>
                  <v-spacer />
                  <v-col class="aligin-center" cols="2">
                    <v-btn
                      text
                      color="blue darken-1"
                      @click="openPublishArea"
                    >
                      <v-icon>mdi-share</v-icon>
                      发布文章
                    </v-btn>
                  </v-col>
                </v-row>
              </v-flex>
              <v-flex>
                <div class="mavonEditor">
                  <mavon-editor
                    ref="mdEditor"
                    v-model="blogContent"
                    :box-shadow="false"
                    :scroll-style="true"
                    :subfield="false"
                    @imgAdd="$imgAdd"
                    @imgDel="$imgDel"
                  />
                </div>
              </v-flex>
            </v-layout>
          </v-card>
          <v-card v-else="" :height="clientHeight">
            <v-card-text>
              快他妈的写点什么吧~
            </v-card-text>
          </v-card>
        </v-sheet>

      </v-flex>
    </v-layout>

    <!--隐藏的对话框-->
    <v-dialog v-model="dialog" persistent max-width="600px">
      <v-card>
        <v-card-title>
          <span class="headline">修改分类</span>
        </v-card-title>
        <v-card-text>
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="dialogValue"
                  label="*分类名称:"
                  :rules="nameRules"
                  required
                />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions class="grid-list-xl justify-center">
          <v-btn color="blue darken-1" text @click="dialog = false">关闭</v-btn>
          <v-btn color="blue darken-1" text @click="updateBlogType">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!--隐藏的提交文章对话框-->
    <v-dialog v-model="showPublish" persistent max-width="800px">
      <v-card>
        <v-card-title>
          <span class="headline">发布文章</span>
        </v-card-title>
        <v-card-text>
          <v-container>
            <v-form
              ref="publishform"
              v-model="pvalid"
              :lazy-validation="lazy"
            >
              <v-sheet width="100%">
                <v-row>
                  <v-col cols="10" class="noPadding">
                    <Mutiselect
                      v-model="blogTags"
                      :options="blogTagList"
                      :multiple="true"
                      placeholder="选择标签"
                      track-by="id"
                      :allow-empty="false"
                      :max="5"
                      label="name"
                    />
                  </v-col>
                  <v-col cols="2" class="noPadding">
                    <v-btn small fab dark color="blue" @click="tagAlert = !tagAlert">
                      <v-icon>mdi-plus</v-icon>
                    </v-btn>
                  </v-col>
                </v-row>
                <div class="mt-2">
                  <v-alert
                    :value="tagAlert"
                    color="#ffffff"
                    dense
                    transition="scale-transition"
                  >
                    <v-card>
                      <v-form
                        ref="tagForm"
                        v-model="valid"
                        :lazy-validation="lazy"
                      >
                        <v-row>
                          <v-col cols="9">
                            <v-text-field
                              v-model="tagName"
                              :rules="nameRules"
                              :counter="10"
                              label="标签名称"
                              prepend-icon="mdi-tag-multiple-outline"
                              required
                            />
                          </v-col>
                          <v-col cols="3" align-self="end">
                            <v-btn x-small fab color="green lighten-3" @click="addBlogTag">
                              <v-icon>mdi-check</v-icon>
                            </v-btn>
                            <v-btn
                              x-small
                              fab
                              color="red lighten-3"
                              class="ml-5"
                              @click="closeTagArea"
                            >
                              <v-icon>mdi-close</v-icon>
                            </v-btn>
                          </v-col>
                        </v-row>

                      </v-form>
                    </v-card>
                  </v-alert>
                </div>
                <v-row class="mt-5">
                  <v-textarea
                    v-model="intro"
                    :auto-grow="true"
                    :clearable="true"
                    :counter="false"
                    hint="在这里写文章简介，这个很关键"
                    label="文章简介"
                    :no-resize="true"
                    :persistent-hint="true"
                    placeholder="请输入点内容，但是别写作文（500个字以内）"
                    :rounded="true"
                    :row-height="24"
                    :rows="8"
                    :shaped="true"
                    :solo="true"
                    :rules="introRules"
                    require
                  />
                </v-row>
              </v-sheet>
            </v-form>
          </v-container>
        </v-card-text>
        <v-card-actions class="grid-list-xl justify-center">
          <v-btn dark color="deep-orange accent-1" @click="clearPublishArea">算了</v-btn>
          <v-btn dark color="teal lighten-2" @click="updateBlog">发布</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-content>
</template>

<script>
import '@/assets/css/business/blog/newblog/newblog.scss'
import {
  getBlogTypes,
  getBlogsByType,
  addBlog,
  addBlogTag,
  updateBlogType,
  deleteBlogType,
  deleteBlog,
  addBlogType,
  getBlogTags,
  updateBlog,
  uploadImage
} from '@/api/blog'

export default {
  name: 'NewBlog',
  data: () => ({
    clientHeight: '',
    blogTypes: [],
    blogs: [],
    typeList: '',
    currentType: '', // 当前选中的分类
    currentId: '', // 当前博客的ID
    articleList: '',
    alert: false,
    tagAlert: false,
    nameRules: [
      v => !!v || '不能为空',
      v => (v && v.length <= 10) || '不能超过10个字符'
    ],
    sortName: '', // 分类名称
    tagName: '', // 标签名称
    dialogValue: '', // 对话框名称
    dialogId: '', // 对话框所属的 blogTypeId
    valid: true, // 是否通过验证
    lazy: false,
    dialog: false, // 修改分类 对话框
    editSN: '', // 分类model
    blogContent: '', // 博客内容
    blogNameRules: [
      v => !!v || '不能为空',
      v => (v && v.length <= 50) || '不能超过50个字符'
    ],
    blogTitle: '', // 博客标题
    editorShow: false, // 是否显示编辑区域
    showPublish: false, // 是否显示发布文章对话框
    blogTags: [], // 文章标签
    blogTagList: [], // 已有的文章标签列表
    intro: '', // 文章简介
    pvalid: true, // 发布表单是否通过验证
    introRules: [
      v => !!v || '简介不能为空'
    ],
    imgFile: []
  }),
  mounted() {
    this.initClientWidth()
    this.initData()
  },
  methods: {
    // 初始化数据
    initData() {
      this.getBlogTypes()
    },
    // 获取博客类型列表
    getBlogTypes() {
      getBlogTypes()
        .then((res) => {
          const result = res.data
          if (res && res.code === 200) {
            this.blogTypes = []
            this.blogs = []
            this.articleList = ''
            this.blogTypes.push(...result)
          }
        })
    },
    // 根据博客类型获取博客列表
    getBlogsByType(blogType) {
      // 选中拦截  点击之前的状态是 true 则拦截此次点击，并清空当前选中的 currentType 值
      this.$nextTick(() => {
        if (this.typeList === undefined) {
          this.currentType = ''
          // 清空博客列表
          this.blogs = []
          this.articleList = ''
          this.clearEditorArea()
          return
        }
        this.getBlogs(blogType)
      })
    },
    getBlogs(blogType) {
      const params = {
        blogType: blogType
      }
      getBlogsByType(params)
        .then((res) => {
          const result = res.data
          if (res && res.code === 200) {
            this.blogs = []
            this.blogs.push(...result)
            this.clearEditorArea()
            // 赋值当前选中的分类
            this.currentType = blogType
            // 取消所有选中的文章
            this.articleList = ''
            // console.log("当前的currentType是：" + this.currentType + "当前typeList是" + this.typeList);
          }
        })
        .catch((err) => {
          // console.log("根据博客类型获取博客列表失败", err)
        })
    },
    // 打开编辑弹窗
    openEditDialog(id, value) {
      this.dialogValue = value
      this.dialogId = id
      this.dialog = true
    },
    // 显示 markdown编辑区域
    showEditorArea(blog) {
      this.$nextTick(() => {
        this.clearEditorArea()
        // 切换文章 富文本区域赋值
        this.editorShow = true
        this.blogTitle = blog.title
        this.currentId = blog.id
        this.blogContent = blog.blogContent
        // 发布区域赋值
        this.intro = blog.intro
        this.blogTags = blog.tags
      })
    },
    // 清空编辑区域内容
    clearEditorArea() {
      // 清空富文本区域
      this.editorShow = false
      this.blogTitle = ''
      this.blogContent = ''
      // 清空发布区域
      this.intro = ''
      this.blogTagList = []
    },
    // 新建当前分类下的 文章
    newArticle() {
      if (this.currentType === '') {
        this.$iziToast.warning({ message: '请先选一个分类吧!' })
        return
      }
      const blogTitle = this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      const params = {
        title: blogTitle,
        blogType: this.currentType,
        blogTypeId: this.currentType
      }
      // 添加一个草稿
      addBlog(params)
        .then((res) => {
          const resultMessage = res.msg
          if (res && res.code === 200) {
            // 重新查询该分类下的文章信息 并重新复制 blogs
            this.getBlogs(this.currentType)
            // 激活 mavonEditor,并赋值title
            this.blogTitle = blogTitle
          }
          if (res && res.code === 500) {
            this.$iziToast.error({ message: resultMessage })
          }
        })
        .catch((err) => {
          // console.log("新增文章失败", err)
        })
    },
    // 编辑博客类型
    updateBlogType() {
      const params = {
        id: this.dialogId,
        name: this.dialogValue
      }
      updateBlogType(params)
        .then((res) => {
          if (res && res.code === 200) {
            // 重新渲染
            this.getBlogTypes()
            this.alert = false
            this.$iziToast.success({ message: res.msg })
          }
          if (res && res.code === 500) {
            this.$iziToast.error({ message: res.msg })
          }
          this.dialog = false
        })
        .catch((err) => {
          // console.log("编辑博客类型失败", err)
        })
    },

    // 删除博客类型
    deleteBlogType(id) {
      const params = {
        id: id
      }
      deleteBlogType(params)
        .then((res) => {
          if (res && res.code === 200) {
            // 重新渲染
            this.getBlogTypes()
            this.alert = false
            this.$iziToast.success({ message: res.msg })
          }
          if (res && res.code === 500) {
            this.$iziToast.error({ message: res.msg })
          }
          this.dialog = false
        })
        .catch((err) => {
          // console.log("删除博客类型失败", err)
        })
    },

    // 删除博客内容
    deleteBlog(blogId) {
      const params = {
        id: blogId
      }
      deleteBlog(params)
        .then((res) => {
          if (res && res.code === 200) {
            // 重新渲染
            this.getBlogs(this.currentType)
            this.clearEditorArea()
            this.$iziToast.success({ message: res.msg })
          }
          if (res && res.code === 500) {
            this.$iziToast.error({ message: res.msg })
          }
          this.dialog = false
        })
        .catch((err) => {
          // console.log("删除博客内容失败", err)
        })
    },

    // 添加博客分类
    addBlogType() {
      if (this.$refs.form.validate()) {
        // 表单校验通过
        const params = {
          sortName: this.sortName
        }
        addBlogType(params)
          .then((res) => {
            if (res && res.code === 200) {
              // 重新渲染
              this.getBlogTypes()
              this.$iziToast.success({ message: res.msg })
              this.alert = false
            }
            if (res && res.code === 500) {
              this.$iziToast.error({ message: res.msg })
            }
          })
          .catch((err) => {
            // console.log("添加博客分类失败", err)
          })
      }
    },

    // 动态监控屏幕宽高比
    initClientWidth() {
      // 获取浏览器可视区域高度
      this.clientHeight = `${document.documentElement.clientHeight}`
      const _that = this
      window.onresize = function temp() {
        _that.clientHeight = `${document.documentElement.clientHeight}`
      }
    },

    // 打开发布博客界面
    openPublishArea() {
      this.showPublish = true
      getBlogTags()
        .then((res) => {
          if (res && res.code === 200) {
            this.blogTagList = []
            this.blogTagList.push(...res.data)
          }
        })
        .catch((err) => {
          // console.log("获取博客标签列表失败", err)
        })
    },

    // 更新博客内容
    updateBlog() {
      if (this.$refs.publishform.validate()) {
        if (!this.blogTags) {
          this.$iziToast.warning({ message: '至少选择一个文章标签，听话！' })
          return
        }
        const params = {
          id: this.currentId,
          blogTagList: JSON.stringify(this.blogTags),
          intro: this.intro,
          blogType: this.currentType,
          title: this.blogTitle,
          blogContent: this.blogContent
        }
        updateBlog(params)
          .then((res) => {
            if (res && res.code === 200) {
              this.$iziToast.success({ message: res.msg })
              // 重新渲染当前分类的博客,因为名称可能有变化
              this.getBlogs(this.currentType)
            }
            this.showPublish = false
          })
          .catch((err) => {
            // console.log("更新博客内容失败", err)
          })
      }
    },
    // 清空发布区域的内容
    clearPublishArea() {
      this.showPublish = false
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      const that = this
      var formdata = new FormData()
      formdata.append('image', $file)
      this.imgFile[pos] = $file
      // console.log("准备将图片上传到服务器");
      uploadImage(formdata)
        .then((res) => {
          if (res && res.code === 500) {
            delete that.imgFile[pos]
            this.$iziToast.error({ message: '上传图片出错了' })
          }
          if (res && res.code === 200) {
            const url = res.data
            // console.log("res:" + res);
            // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
            that.$refs.mdEditor.$img2Url(pos, url)
          }
        })
        .catch((err) => {
          // console.log("上传图片出错", err)
          delete that.imgFile[pos]
          this.$iziToast.error({ message: '上传图片出错了' })
        })
    },
    $imgDel(pos) {
      delete this.imgFile[pos]
    },
    // 添加一个博客标签
    addBlogTag() {
      // console.log("添加博客标签");
      const params = {
        tagName: this.tagName
      }
      addBlogTag(params)
        .then((res) => {
          if (res && res.code === 200) {
            // 1重新渲染下拉 2关闭添加框 3清空tag表单
            this.blogTagList = []
            this.blogTagList = res.data
            this.resetTagArea()
          }
          if (res && res.code === 500) {
            this.$iziToast.error({ message: res.msg })
          }
        })
        .catch((err) => {
          // console.log("添加博客标签失败", err)
        })
    },
    closeTagArea() {
      this.resetTagArea()
    },
    resetTagArea() {
      this.$refs.tagForm.reset()
      this.tagAlert = false
    }

  }

}
</script>

<style scoped>

</style>
